package com.frxuexi.park2303.news

import android.content.Intent
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.base.entity.NewsBeanItem
import com.frxuexi.base.http.Const
import com.frxuexi.base.mvi.BaseActivity
import com.frxuexi.base.mvi.RequestType
import com.frxuexi.base.mvi.UiState
import com.frxuexi.base.utils.DateTimeUtils
import com.frxuexi.base.utils.GlideUtil
import com.frxuexi.park2303.R
import com.frxuexi.park2303.databinding.ActivityNewsAddBinding
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@Route(path = "/app/NewsAddActivity")
@AndroidEntryPoint
class NewsAddActivity : BaseActivity<ActivityNewsAddBinding,NewsIntent,NewsViewModel>() {
    var type="园区新闻"
    var list= mutableListOf<String>()
    override fun getVM(): NewsViewModel {
        return viewModels<NewsViewModel>().value
    }

    override fun getBind(): ActivityNewsAddBinding {
        return ActivityNewsAddBinding.inflate(layoutInflater)
    }

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                       when(it.type){
                           RequestType.UPLOAD->{
                               val name = it.data.toString().split(":")[1]
                               list.add("http://10.161.9.80:2209/images/news/${
                                   SPUtils.getInstance().getInt(
                                       Const.UID)}/${name}")
                           }
                           RequestType.ADD->{
                               ToastUtils.showLong("发布成功")
                               finish()
                           }

                           else -> {}
                       }
                    }

                    else -> {}
                }
            }
        }

    }

    override fun initView() {
        binding.newsaddHead.apply {
            headBack.setOnClickListener {
                finish()
            }
            headTitle.setText("发布新闻")
            headAdd.setImageResource(com.frxuexi.base.R.drawable.ic_action_ok)
            headAdd.setOnClickListener {
                val content = binding.newsaddContent.text.toString()
                val date = binding.newsaddDate.text.toString()
                val user = binding.newsaddUser.text.toString()
                val title = binding.newsaddTitle.text.toString()
                val item = NewsBeanItem(
                    false,
                    content,
                    null,
                    list,
                    date,
                    true,
                    user,
                    title,
                    type,0
                )
                vm.sendIntent(NewsIntent.addNews(item))
            }
        }

        binding.newsaddUser.setText(SPUtils.getInstance().getString(Const.UNAME))

        binding.newsaddTitle.addTextChangedListener(object :TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                val length = s?.length

                binding.newsaddNum.apply {
                    setText("${length}/50")
                    if(length==50){
                        setTextColor(Color.RED)
                    }else{
                        setTextColor(Color.DKGRAY)
                    }
                }

            }

            override fun afterTextChanged(s: Editable?) {
            }
        })
        binding.newsaddDate.setText(DateTimeUtils.getDate(System.currentTimeMillis()))

        binding.newaddIvdate.setOnClickListener {
            showDateDialog {
                binding.newsaddDate.setText(it)
            }
        }

        val typeList = listOf<String>("园区新闻", "广告")
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, typeList)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        binding.newsaddType.adapter=adapter
        binding.newsaddType.onItemSelectedListener=object :OnItemSelectedListener{
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                type=typeList[position]
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
            }
        }

        binding.newsaddIv.setOnClickListener {
            PictureSelector.create(this,PictureSelector.SELECT_REQUEST_CODE).selectPicture()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==PictureSelector.SELECT_REQUEST_CODE && resultCode== RESULT_OK){
            val path = data?.extras?.getParcelable<PictureBean>(PictureSelector.PICTURE_RESULT)?.path!!
            GlideUtil.loadRoundImage(binding.newsaddIv,path)
            val split = path.split("/")
            val name = split.get(split.lastIndex)
            vm.sendIntent(NewsIntent.uploadNews(name,path))
        }
    }

}